<template>
  <div class="repository-create-page">
    <div class="page-container">
      <div class="page-header">
        <h2 class="page-title">添加代码库</h2>
        <el-button @click="$router.back()">返回</el-button>
      </div>

      <el-form
        ref="repoFormRef"
        :model="repoForm"
        :rules="repoRules"
        label-width="120px"
        class="form-container"
      >
        <!-- 基本信息 -->
        <el-card class="form-section" header="基本信息">
          <el-form-item label="仓库名称" prop="name">
            <el-input
              v-model="repoForm.name"
              placeholder="请输入仓库名称"
              maxlength="100"
              show-word-limit
            />
          </el-form-item>

          <el-form-item label="仓库类型" prop="type">
            <el-radio-group v-model="repoForm.type">
              <el-radio label="source">源代码库</el-radio>
              <el-radio label="target">目标代码库</el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item label="仓库平台" prop="platform">
            <el-select
              v-model="repoForm.platform"
              placeholder="请选择仓库平台"
              style="width: 100%"
              @change="handlePlatformChange"
            >
              <el-option label="阿里云效 (Codeup)" value="codeup" />
              <el-option label="AtomGit" value="atomgit" />
              <el-option label="GitCode" value="gitcode" />
              <el-option label="GitHub" value="github" />
              <el-option label="Gitee" value="gitee" />
              <el-option label="GitLab" value="gitlab" />
            </el-select>
          </el-form-item>

          <el-form-item label="仓库地址" prop="url">
            <el-input
              v-model="repoForm.url"
              placeholder="请输入仓库地址，如: https://github.com/user/repo.git"
            />
          </el-form-item>

          <el-form-item label="默认分支" prop="default_branch">
            <el-input
              v-model="repoForm.default_branch"
              placeholder="请输入默认分支名称，如: main, master"
            />
          </el-form-item>

          <el-form-item label="描述" prop="description">
            <el-input
              v-model="repoForm.description"
              type="textarea"
              :rows="3"
              placeholder="请输入仓库描述"
              maxlength="500"
              show-word-limit
            />
          </el-form-item>
        </el-card>

        <!-- 认证配置 -->
        <el-card class="form-section" header="认证配置">
          <el-form-item label="认证方式" prop="auth_type">
            <el-select
              v-model="repoForm.auth_type"
              placeholder="请选择认证方式"
              style="width: 100%"
            >
              <el-option label="HTTPS认证" value="https" />
              <el-option label="SSH密钥" value="ssh" />
              <el-option label="访问令牌" value="token" />
            </el-select>
          </el-form-item>

          <!-- HTTPS认证 -->
          <template v-if="repoForm.auth_type === 'https'">
            <el-form-item label="用户名" prop="username">
              <el-input
                v-model="repoForm.username"
                placeholder="请输入用户名"
              />
            </el-form-item>

            <el-form-item label="密码" prop="password">
              <el-input
                v-model="repoForm.password"
                type="password"
                placeholder="请输入密码"
                show-password
              />
            </el-form-item>
          </template>

          <!-- SSH密钥 -->
          <template v-if="repoForm.auth_type === 'ssh'">
            <el-form-item label="私钥" prop="ssh_private_key">
              <el-input
                v-model="repoForm.ssh_private_key"
                type="textarea"
                :rows="6"
                placeholder="请输入SSH私钥内容"
              />
            </el-form-item>

            <el-form-item label="私钥密码" prop="ssh_passphrase">
              <el-input
                v-model="repoForm.ssh_passphrase"
                type="password"
                placeholder="私钥密码（可选）"
                show-password
              />
            </el-form-item>
          </template>

          <!-- 访问令牌 -->
          <template v-if="repoForm.auth_type === 'token'">
            <el-form-item label="访问令牌" prop="access_token">
              <el-input
                v-model="repoForm.access_token"
                type="password"
                placeholder="请输入访问令牌"
                show-password
              />
            </el-form-item>

            <div class="help-text">
              <el-alert
                title="令牌获取说明"
                type="info"
                :closable="false"
                show-icon
              >
                <template #default>
                  <div v-if="repoForm.platform === 'github'">
                    GitHub: 访问 Settings > Developer settings > Personal access tokens 生成
                  </div>
                  <div v-else-if="repoForm.platform === 'gitee'">
                    Gitee: 访问 设置 > 安全设置 > 私人令牌 生成
                  </div>
                  <div v-else-if="repoForm.platform === 'gitlab'">
                    GitLab: 访问 User Settings > Access Tokens 生成
                  </div>
                  <div v-else>
                    请参考对应平台的文档获取访问令牌
                  </div>
                </template>
              </el-alert>
            </div>
          </template>
        </el-card>

        <!-- 高级配置 -->
        <el-card class="form-section" header="高级配置">
          <el-form-item label="启用状态">
            <el-switch
              v-model="repoForm.enabled"
              active-text="启用"
              inactive-text="禁用"
            />
          </el-form-item>

          <el-form-item label="连接超时">
            <el-input-number
              v-model="repoForm.timeout"
              :min="10"
              :max="300"
              :step="10"
              placeholder="连接超时时间（秒）"
            />
            <span style="margin-left: 10px; color: #909399;">秒</span>
          </el-form-item>

          <el-form-item label="代理设置">
            <el-input
              v-model="repoForm.proxy_url"
              placeholder="代理地址（可选）"
            />
          </el-form-item>
        </el-card>

        <!-- 表单操作 -->
        <div class="form-footer">
          <el-button @click="testConnection" :loading="testing">
            <el-icon><Connection /></el-icon>
            测试连接
          </el-button>
          <el-button @click="$router.back()">取消</el-button>
          <el-button @click="resetForm">重置</el-button>
          <el-button type="primary" @click="submitForm" :loading="submitting">
            添加代码库
          </el-button>
        </div>
      </el-form>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Connection } from '@element-plus/icons-vue'
import { repositoryApi } from '../api'

const router = useRouter()

// 表单引用
const repoFormRef = ref()
const submitting = ref(false)
const testing = ref(false)

// 代码库表单数据
const repoForm = reactive({
  name: '',
  type: 'source',
  platform: 'github',
  url: '',
  default_branch: 'main',
  description: '',
  auth_type: 'https',
  username: '',
  password: '',
  ssh_private_key: '',
  ssh_passphrase: '',
  access_token: '',
  enabled: true,
  timeout: 30,
  proxy_url: ''
})

// 表单验证规则
const repoRules = {
  name: [
    { required: true, message: '请输入仓库名称', trigger: 'blur' },
    { min: 2, max: 100, message: '仓库名称长度在 2 到 100 个字符', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择仓库类型', trigger: 'change' }
  ],
  platform: [
    { required: true, message: '请选择仓库平台', trigger: 'change' }
  ],
  url: [
    { required: true, message: '请输入仓库地址', trigger: 'blur' },
    {
      pattern: /^https?:\/\/.+|git@.+:.+\.git$/,
      message: '请输入有效的Git仓库地址',
      trigger: 'blur'
    }
  ],
  default_branch: [
    { required: true, message: '请输入默认分支', trigger: 'blur' }
  ],
  auth_type: [
    { required: true, message: '请选择认证方式', trigger: 'change' }
  ],
  username: [
    {
      validator: (rule, value, callback) => {
        if (repoForm.auth_type === 'https' && !value) {
          callback(new Error('请输入用户名'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  password: [
    {
      validator: (rule, value, callback) => {
        if (repoForm.auth_type === 'https' && !value) {
          callback(new Error('请输入密码'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  ssh_private_key: [
    {
      validator: (rule, value, callback) => {
        if (repoForm.auth_type === 'ssh' && !value) {
          callback(new Error('请输入SSH私钥'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  access_token: [
    {
      validator: (rule, value, callback) => {
        if (repoForm.auth_type === 'token' && !value) {
          callback(new Error('请输入访问令牌'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 处理平台变化
const handlePlatformChange = (platform) => {
  // 根据平台设置默认值
  if (platform === 'codeup') {
    repoForm.default_branch = 'master'
  } else {
    repoForm.default_branch = 'main'
  }
}

// 测试连接
const testConnection = async () => {
  try {
    await repoFormRef.value.validate()

    testing.value = true

    // 构建测试数据
    const testData = {
      ...repoForm,
      status: repoForm.enabled ? 'enabled' : 'disabled'
    }

    const response = await repositoryApi.testConnection(null, testData)

    if (response.data?.success) {
      ElMessage.success('连接测试成功')
    } else {
      ElMessage.error('连接测试失败: ' + (response.data?.message || '未知错误'))
    }
  } catch (error) {
    console.error('连接测试失败:', error)
    ElMessage.error('连接测试失败')
  } finally {
    testing.value = false
  }
}

// 提交表单
const submitForm = async () => {
  try {
    await repoFormRef.value.validate()

    submitting.value = true

    // 构建提交数据
    const submitData = {
      ...repoForm,
      status: repoForm.enabled ? 'enabled' : 'disabled'
    }

    // 移除前端专用字段
    delete submitData.enabled

    await repositoryApi.createRepository(submitData)
    ElMessage.success('代码库添加成功')
    router.push('/repositories')
  } catch (error) {
    console.error('添加代码库失败:', error)
    if (error.message) {
      ElMessage.error(error.message)
    }
  } finally {
    submitting.value = false
  }
}

// 重置表单
const resetForm = () => {
  repoFormRef.value?.resetFields()
  // 重置为默认值
  repoForm.type = 'source'
  repoForm.platform = 'github'
  repoForm.default_branch = 'main'
  repoForm.auth_type = 'https'
  repoForm.enabled = true
  repoForm.timeout = 30
}

// 页面加载时的处理
onMounted(() => {
  // 可以在这里进行初始化操作
})
</script>

<style scoped>
.repository-create-page {
  padding: 0;
}

.form-container {
  max-width: 800px;
  margin: 0 auto;
}

.form-section {
  margin-bottom: 20px;
}

.help-text {
  margin-top: 10px;
}

.form-footer {
  text-align: center;
  margin-top: 30px;
}

.form-footer .el-button {
  margin: 0 5px;
}
</style>
